package com.yyge.common.aspect;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.yyge.common.util.WaimaiThreadLocal;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;
@Component
public class MybatisPlusMetaObjectHandler implements MetaObjectHandler {

    /**
     * 调用mybatisplus  save()方法
     * @param metaObject  真实的对象（实体对象）
     */
    @Override
    public void insertFill(MetaObject metaObject) {

        System.out.println("isDefault");
        metaObject.setValue("createTime",new Date());
        metaObject.setValue("updateTime",new Date());
        if(WaimaiThreadLocal.getCurrent()!=null){
         this.strictInsertFill(metaObject, "createBy", String.class, WaimaiThreadLocal.getName());
        }

        if(WaimaiThreadLocal.mobileLoginThreadLocal!=null){
        /**
         * 在使用SetValue的时候一定要在实体类上面添加 Value的对应数据库列 否则回填充失败
         */
         metaObject.setValue("createBy", WaimaiThreadLocal.mobileLoginThreadLocal.get().getUserName());
         metaObject.setValue("updateBy", WaimaiThreadLocal.mobileLoginThreadLocal.get().getUserName());

         //以下是获取所有属性名称,可通过属性名称来遍历值
         /*String[] names = metaObject.getGetterNames();

        for (String name : names) {
            Object value = metaObject.getValue(name);
            System.out.println(name+"==="+value);
        }*/
        //this.findTableInfo(metaObject);
        }
    }


    /**
     * 调用mybatisplus  updateById()方法
     * @param metaObject 真实的对象（实体对象）
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "updateTime", Date.class, new Date());
        if(WaimaiThreadLocal.getCurrent()!=null) {
            this.strictInsertFill(metaObject, "updateBy", String.class, WaimaiThreadLocal.getName());
        }
        if(WaimaiThreadLocal.mobileLoginThreadLocal!=null){
         this.strictInsertFill(metaObject, "updateBy", String.class, WaimaiThreadLocal.mobileLoginThreadLocal.get().getUserName());
        }
    }
}
